<?php

namespace App\Libs\Helper;

/**
 * 树形结构帮助方法
 * @package App\Libs\Helper
 */
trait TreeHelper
{

    /**
     * 将给定数据转换为树形结构数组
     * @param $entities
     * @param array $arr
     * @param int $parent_id
     * @param int $level
     * @return array
     */
    public static function getTreeArray($entities, $arr = [], $parent_id = 0, $level = 0)
    {
        foreach ($entities as $entity) {
            if ($entity->parent_id == $parent_id) {
                array_push($arr, [$entity->id, $entity->name, $level, $entity->parent_id]);
                $arr = self::getTreeArray($entities, $arr, $entity->id, $level + 1);
            }
        }
        return $arr;
    }

    /**
     * 通过给定ID获取该对象所有的子类ID
     * @param $id
     * @param array $arr
     * @return array
     */
    public static function getAllChildrenIds($id, $arr = [])
    {
        $entities = self::find($id)->childrenCategories;
        if (!$entities->isEmpty()) {
            foreach ($entities as $entity) {
                array_push($arr, $entity->id);
                $arr = self::getAllChildrenIds($entity->id, $arr);
            }
        }
        return $arr;
    }

}